﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using myBoard.App.Components.MagnetsStore.ViewsModels;
using System.Net;
using System.IO;
using myBoard.Framework;
using myBoard.App.Model;
using ICSharpCode.SharpZipLib.Zip;
using myBoard.App.Business;

namespace myBoard.App.Components.MagnetsStore.Commands
{
    public class DownloadMagnetCommand : ICommand
    {
        bool _alreadyDownloaded;

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            if (_alreadyDownloaded)
                return false;

            foreach (MagnetEx installedMagnet in InstancesSingleton.Instances.InstalledMagnets)
            {
                if (installedMagnet.StoreID == InstancesSingleton.Instances.MagnetsViewModel.SelectedMagnet.StoreID &&
                    InstancesSingleton.Instances.MagnetsViewModel.SelectedMagnet.Version == string.Format("{0}.{1}", installedMagnet.Version.Major, installedMagnet.Version.Minor))
                {
                    return false;
                }
            }            
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            MagnetViewModel mvm = parameter as MagnetViewModel;
            WebClient webClient = new WebClient();
            bool upgradeDetected = false;
            string mgtPath = Path.GetTempFileName();
            string destPath = Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("AppData"), "myBoard"), "Magnets");
            webClient.DownloadFileCompleted += (sender, e) =>
                {
                    _alreadyDownloaded = true;
                    if (CanExecuteChanged != null)
                        CanExecuteChanged(this, null);

                    if(upgradeDetected)
                    {
                        ExtractMagnet(mgtPath, destPath);
                        myBoard.Framework.Forms.MessageBox.Show("Download completed !",
                            string.Format("{0} download is now completed. This being an upgrade of a currently installed magnet, myBoard must restart so you can start using this magnet.", mvm.Name),
                            "Magnet Store");
                        Launcher.RestartMyBoard();
                    }
                    else
                    {
                        ExtractMagnet(mgtPath, destPath);
                        MagnetsManager.GetInstalledMagnets();
                        myBoard.Framework.Forms.MessageBox.Show("Download completed !",
                            string.Format("{0} download is now completed, you can now start enjoying it using the magnets explorer.",mvm.Name),
                            "Magnet Store");                        
                    }
                };
            webClient.DownloadProgressChanged += (sender, e) =>
                {
                    mvm.DownloadProgress = e.ProgressPercentage;
                };
            
            if (!Directory.Exists(destPath))
                Directory.CreateDirectory(destPath);
            string subDirectoryName = mvm.Name;

            if (Directory.Exists(Path.Combine(destPath, subDirectoryName)))
            {                
                int i = 1;
                do
                {
                    i++;
                } while (Directory.Exists(Path.Combine(destPath, string.Format("{0}-{1}", i, subDirectoryName))));
                subDirectoryName = string.Format("{0}-{1}", i, subDirectoryName);
            }
            destPath = Path.Combine(destPath, subDirectoryName);

            foreach (MagnetEx installedMagnet in InstancesSingleton.Instances.InstalledMagnets)
            {
                //let's delete the old magnet
                if (installedMagnet.StoreID == mvm.StoreID)
                {
                    myBoard.App.Model.InstancesSingleton.Instances.CurrentConfiguration.MagnetsToDeleteOnNextStart.Add(installedMagnet.FullyQualifiedName);
                    ConfigurationSerializer s = new ConfigurationSerializer();
                    s.Serialize(myBoard.App.Model.InstancesSingleton.Instances.CurrentConfiguration);

                    string serializedPath = Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("AppData"), "myBoard"), "magnets.xml");
                    if (File.Exists(serializedPath))
                    {
                        MagnetsSerializer ms = new MagnetsSerializer();
                        List<MagnetEx> magnets = ms.DeSerialize(serializedPath);
                        foreach (MagnetEx m in magnets)
                        {
                            if (m.FullyQualifiedName == installedMagnet.FullyQualifiedName)
                            {
                                m.FullyQualifiedName = Path.Combine(destPath, Path.GetFileName(m.FullyQualifiedName));
                            }
                        }
                        ms.Serialize(magnets, Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("AppData"), "myBoard"), "magnets.xml"));
                    }

                    upgradeDetected = true;
                }
            }

            webClient.DownloadFileAsync(new Uri(mvm._magnet.DownloadUrl), mgtPath);
        }

        private void ExtractMagnet(string mgtPath,string extractionPath)
        {
            string destPath = Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("AppData"), "myBoard"), "Magnets");
            FastZip fastzip = new FastZip();
            fastzip.ExtractZip(mgtPath, extractionPath, null);
            File.Delete(mgtPath);
        }

        #endregion
    }
}
